package cn.com.guage.dynamic.datasource.config;

import java.io.IOException;
import java.util.Map;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import com.alibaba.druid.pool.DruidDataSource;
import com.google.common.collect.Maps;

/**
 * 定义数据库实体类并配置为多数据源的形式
 *
 * @author yangdechao
 * @version 1.0
 * @date 2020/07/14 16:36
 */
@Configuration
@MapperScan(basePackages = "cn.com.guage.dynamic.datasource.mapper", sqlSessionFactoryRef = "sqlSessionFactory")
public class DatasourceConfig {
	@Resource
	@Qualifier(Datasources.DB1)
	private DataSource db1;

	@Resource
	@Qualifier(Datasources.DB2)
	private DataSource db2;

	/**
	 * destroy-method="close"的作用是当数据库连接不使用的时候,就把该连接重新放到数据池中,方便下次使用调用.
	 */
	@Bean(destroyMethod = "close", name = Datasources.DB1)
	@ConfigurationProperties(prefix = "spring.datasource.db1")
	public DataSource dataSource() {
		return DataSourceBuilder.create().type(DruidDataSource.class).build();
	}

	@Bean(destroyMethod = "close", name = Datasources.DB2)
	@ConfigurationProperties(prefix = "spring.datasource.db2")
	public DataSource dataSourceSlave() {
		return DataSourceBuilder.create().type(DruidDataSource.class).build();
	}

	/**
	 * 多数据源配置
	 *
	 * @return DataSource
	 */
	@Bean(name = "dynamicDataSource")
	public DataSource dynamicDataSource() {
		DynamicDataSource dynamicDataSource = new DynamicDataSource();
		dynamicDataSource.setDefaultTargetDataSource(db1);
		Map<Object, Object> dsMap = Maps.newHashMap();
		dsMap.put(Datasources.DB1, db1);
		dsMap.put(Datasources.DB2, db2);
		dynamicDataSource.setTargetDataSources(dsMap);
		return dynamicDataSource;
	}

	@Bean(name = "sqlSessionFactory")
	public SqlSessionFactoryBean sqlSessionFactoryBean() {
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		sqlSessionFactoryBean.setDataSource(dynamicDataSource());
		try {
			sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapping/*.xml"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sqlSessionFactoryBean;
	}
}